package com.tbit.uqbike.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.common.dao.OssLogDao;
import com.tbit.common.entity.RefundLog;
import com.tbit.common.entity.ReturnLog;
import com.tbit.common.entity.UserAccountMoney;
import com.tbit.uqbike.center.pojo.MachineStatus;
import com.tbit.uqbike.client.constant.*;
import com.tbit.uqbike.client.constant.annotation.PreventDuplication;
import com.tbit.uqbike.client.constant.annotation.TestAnnotation;
import com.tbit.uqbike.client.dao.capital.RefundLogDao;
import com.tbit.uqbike.client.dao.core.ParkPointVertDao;
import com.tbit.uqbike.client.dao.ter.TerAttrExDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.*;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.*;

/**
 * 调试
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 * @ignore
 */
@Controller
@RequestMapping("/debug")
public class DebugController {
    public static Map<String, AppOperaLog> logMap = new HashMap<>();
    @Autowired
    private MachineStatusConsumerService machineStatusConsumerService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private TerAttrExDao terAttrExDao;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private ParkPointVertDao parkPointVertDao;
    @Autowired
    private UserService userService;
    @Autowired
    private MQProducer mqProducer;
    @Autowired
    private PushMsgLogService pushMsgLogService;
    @Autowired
    private OssLogDao ossLogDao;
    @Autowired
    private RefundLogDao refundLogDao;
    @Autowired
    private UserAccountMoneyService userAccountMoneyService;
    @Autowired
    private UserWxzffService userWxzffService;

    /* 测试 */
    @RequestMapping("/test")
    public void test(Integer machineId, HttpSession session, HttpServletRequest request,
                     HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<Integer> machineIds = new ArrayList<Integer>();
            machineIds.add(machineId);

            List<MachineStatus> machineStatuses = machineStatusConsumerService.getByMachineIds(machineIds);

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, machineStatuses);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /* 测试 */
    @RequestMapping("/addLog")
    public void addLog(AppOperaLog appOperaLog, HttpSession session, HttpServletRequest request,
                       HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            //logMap.put(appOperaLog.getMachineNO(),appOperaLog);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /* 测试 */
    @PreventDuplication(expireSeconds = 60)
    @RequestMapping("/add")
    public void add(String token, HttpSession session, HttpServletRequest request,
                    HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            System.out.println(token);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /* 测试 */
    @RequestMapping("/get")
    @TestAnnotation(expireSeconds = 5)
    public void get(String token, String machineNO, HttpSession session, HttpServletRequest request,
                    HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        long time = System.currentTimeMillis();
        try {
            byte[] dataByte = Base64.decodeBase64("dad");
            byte[] keyByte = Base64.decodeBase64("33");
            byte[] ivByte = Base64.decodeBase64("3");

            try {
                // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
                int base = 16;
                if (keyByte.length % base != 0) {
                    int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                    byte[] temp = new byte[groups * base];
                    Arrays.fill(temp, (byte) 0);
                    System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                    keyByte = temp;
                }
                // 初始化
                Security.addProvider(new BouncyCastleProvider());
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
                SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
                AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
                parameters.init(new IvParameterSpec(ivByte));
                cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
                byte[] resultByte = cipher.doFinal(dataByte);
                if (null != resultByte && resultByte.length > 0) {
                    String result = new String(resultByte, "UTF-8");
                    JSONObject object = JSONObject.parseObject(result);
                    System.out.println(object.getString("phoneNumber") + "，耗时【" + (System.currentTimeMillis() - time) + "】毫秒");
                    ;
                }
                System.out.println("执行方法耗时【" + (System.currentTimeMillis() - time) + "】毫秒");
                ;
            } catch (Exception e) {
                System.out.println(("获取微信用户手机号码异常：" + e.getMessage()));
            }


        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 类型查询
     *
     * @param type     1、垂直停车。2、道钉。*3、头盔锁。4、脚撑。5、位置、电量。
     * @param userCode 车辆编号
     * @param request
     * @param response
     */
    @RequestMapping("/getByType")
    public void getByType(Integer type, String userCode, HttpServletRequest request,
                          HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Assert.notNull(type, "-170010", "类型不能为空");
            Assert.notNull(userCode, "-30006", "用户码不能为空");
            Machine machine = machineService.getByUserCode(userCode);
            if (machine == null) {
                throw new BaseException("-30005", "设备不存在");
            }
            if (type == 1) {
                Map<String, Object> attrMap = new HashMap<>();
                attrMap.put("machineNO", machine.getMachineNO());
                attrMap.put("name", "tLD");
                TerAttrEx terAttrEx = terAttrExDao.getByMachineNO(attrMap);
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("上报时间=" + DateTimeUtil.DateTimeToString(terAttrEx.getDt()));
                stringBuffer.append(",系统时间=" + DateTimeUtil.getNowTime());
                stringBuffer.append(",终端角度=" + (Double.valueOf(terAttrEx.getValue()) / 10));
				/*Integer parkPointId = machineService.isInParkPoint(248,machine.getMachineNO(),null,2);
				if(parkPointId!=null){
					ParkPointVert parkPointVert = parkPointVertDao.getByParkPointId(parkPointId);
					if(parkPointVert!=null){
						String [] strings = parkPointVert.getPoints().split(";");
						*//**只取前两个点*//*
						String [] strings1 = strings[0].split(",");
						String [] strings2 = strings[1].split(",");
						MyLatLng myLatLng = new MyLatLng(Double.parseDouble(strings1[0]),Double.parseDouble(strings1[1]));
						MyLatLng myLatLng1 = new MyLatLng(Double.parseDouble(strings2[0]),Double.parseDouble(strings2[1]));
						double tmp= GeoUtil.getAngle(myLatLng,myLatLng1);
						stringBuffer.append(",平台与正北夹角="+tmp);
					}
				}*/
                map.put(ResponseCode.DATA, stringBuffer);
            } else if (type == 2) {
                String tmp = redisService.get(RedisConstant.MACHINE_NO_BLEINFO + machine.getMachineNO());
                List<BleInfo> list = JSON.parseArray(tmp, BleInfo.class);
                if (list != null && list.size() > 0) {
                    for (BleInfo bleInfo : list) {
                        bleInfo.setDate(DateTimeUtil.DateTimeToString(new Date(bleInfo.getUpdateTime())));
                    }
                }
                map.put(ResponseCode.DATA, list);
            } else if (type == 3) {
                String json = redisService.getMain(
                        RedisUtil.getTerHashId(machine.getMachineNO()), RedisConstant.REDIS_TER_LAST_STATUS);
                if (json != null && json.length() > 0) {
                    TerLastStatus terLastStatus = JSON.parseObject(json, TerLastStatus.class);
                    Integer terStatus = terLastStatus.getCarStatus();
                    map.put(ResponseCode.DATA, ObjectUtil.statusParse(11, terStatus));
                } else {
                    map.put(ResponseCode.DATA, false);
                }
            } else if (type == 4) {

            } else if (type == 5) {
                MachineStatus machineStatus = machineStatusService.getByMachineNO(machine.getMachineNO(),
                        MapConstant.MAP_GOOGLE);
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("车辆编号=" + userCode + ",");
                stringBuffer.append("电池时间=" + machineStatus.getBatDt() + ",");
                stringBuffer.append("电量=" + machineStatus.getSocPercent() + ",");
                stringBuffer.append("电压=" + machineStatus.getBatteryEU() + ",");
                stringBuffer.append("定位时间=" + machineStatus.getPosDt() + ",");
                stringBuffer.append("经度=" + machineStatus.getLon() + ",");
                stringBuffer.append("纬度=" + machineStatus.getLat());
                map.put(ResponseCode.DATA, stringBuffer);
            }
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);

    }

    /**
     * 刷新品牌配置
     *
     * @param accountId
     * @param configType
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping("/fresh")
    public void fresh(Integer accountId, Integer configType, HttpSession session,
                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            redisService.del(RedisConstant.ACCOUNTCONFIG_KEY_PREFIX + accountId + "." + configType);
            map.put(ResponseCode.RET, ResponseCode.SUCC);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    @RequestMapping("/delOpenId")
    public void delOpenId(Integer accountId, String phone, Integer configType, HttpSession session,
                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = userService.getByAccountIdAndPhone(accountId, phone);
            if (user != null) {
                userWxzffService.del(user.getUserId());
            }
            map.put(ResponseCode.RET, ResponseCode.SUCC);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 清除redis数据
     *
     * @param key
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping("/del")
    public void del(String key, HttpSession session, HttpServletRequest request,
                    HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            redisService.del(key);
            map.put(ResponseCode.RET, ResponseCode.SUCC);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /* 测试 */
    @RequestMapping("/log")
    public void log(String tmp, String phone, HttpSession session, HttpServletRequest request,
                    HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            //System.out.println("手机号码="+phone+"tmp"+tmp);
            LogUtil.info("手机号码=" + phone + ",tmp=" + tmp);
            map.put(ResponseCode.RET, ResponseCode.SUCC);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    /**
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping("/sendMq")
    public void sendMq(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            mqProducer.sendPay("GXBIKE123456789", "", "321323123131", "2022-08-18 15:00:00", null);
            map.put(ResponseCode.RET, ResponseCode.SUCC);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    @RequestMapping("/sendAck")
    public void sendAck(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Machine machine = machineService.getByMachineNO("019171868");
            redisService.add(FunctionConstant.VERTICAL + machine.getMachineNO(), "407", 60);
            redisService.add(RedisConstant.LOG_SIGN + machine.getMachineNO(), "502", 60);
            AccountConfig accountConfig = new AccountConfig();
            accountConfig.setOffsetAngle(20);
            accountConfig.setReturnTimes(3);
            accountConfig.setVerticalPark(1);
            machineService.isVertical(accountConfig, machine, 1, "202302521545", 557740, null, 1);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    @RequestMapping("/getByAccountId")
    public void getByAccountId(String orderNO, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<ReturnLog> returnLogs = ossLogDao.getByAccountId();
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, returnLogs);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    @RequestMapping("/getConstant")
    public void getConstant(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, SystemConstant.operaPsw);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    @RequestMapping("/getRefundLogId")
    public void getRefundLogId(String orderNO, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            List<RefundLog> refundLog = refundLogDao.selectByOrderId(orderNO);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, refundLog);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    @RequestMapping("/getUserAccountMoney")
    public void getUserAccountMoney(Integer userId, Integer moneyType, Integer accountId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            UserAccountMoney userAccountMoney = userAccountMoneyService.getByAccountId(userId, moneyType, accountId);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, userAccountMoney);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

}